package sourceagile.server.githubFileRepository;

import java.util.List;
import java.util.Map;

import org.codehaus.jettison.json.JSONArray;

import sourceagile.server.subversionFileRepository.ConvertFileToJson;

import com.github.api.v2.schema.Repository;
import com.github.api.v2.schema.Tree;
import com.github.api.v2.services.GitHubServiceFactory;
import com.github.api.v2.services.ObjectService;
import com.github.api.v2.services.RepositoryService;

public class ListGithubFiles {

	public static JSONArray listEntries(String username, String projectName) {

		JSONArray entries = new JSONArray();

		GitHubServiceFactory factory = GitHubServiceFactory.newInstance();

		String masterSHA = getMasterRepositorySha(factory, username,
				projectName);

		ObjectService objectService = factory.createObjectService();

		List<Tree> trees = objectService.getTree(username, projectName,
				masterSHA);

		for (Tree tree : trees) {

			entries.put(ConvertFileToJson.convertFromGithub(tree));
		}

		return entries;
	}

	public static String getMasterRepositorySha(GitHubServiceFactory factory,
			String username, String projectName) {

		RepositoryService service = factory.createRepositoryService();

		// service.setAuthentication(new LoginTokenAuthentication("allineo",
		// "luizinho0820"));

		Map<String, String> branches = service.getBranches(username,
				projectName);

		String masterSHA = branches.get(Repository.MASTER);

		return masterSHA;
	}
}
